import cv2
import numpy as np
from PIL import ImageGrab, Image
from main import *
import win32gui, win32con, os
from File import Json
surprise = 0

# 分辨率 1280 800

class Images:
    choosetask = "img\\choosetask.png"
    start_point = "img\\startpoint.png"
    first_battle = "img\\first_battle.png"
    skill_panel_bg = "img\\skill_panel_bg.png"
    choose_treasure = "img\\choose_treasure.png"
    line = "img\\line.png"
    surprise = "img\\surprise.png"
    end = "img\\end.png"
    visitor = "img\\visitor.png"
    battle = "img\\battle.png"
    choose_treasure2 = "img\\choose_treasure2.png"
    ready = "img\\ready.png"

class Icons:
    def __init__(self):
        for k, v in Images.__dict__.items():
            # print(k, v)
            if not k.startswith('_'):
                # f_path = os.path.join(os.getcwd(), v)
                # print(f_path)
                setattr(self, k, self.fname2img(v))

    @staticmethod
    def fname2img(fname):
        # print(cv2.imread(fname))
        res = cv2.cvtColor(cv2.imread(fname), cv2.COLOR_BGR2GRAY)
        return res

def find_lushi_window():
    hwnd = findTopWindow("炉石传说")
    win32gui.SetWindowPos(hwnd, win32con.HWND_TOPMOST, 0,0,0,0, win32con.SWP_NOMOVE | win32con.SWP_NOSIZE)
    rect = win32gui.GetWindowPlacement(hwnd)[-1]
    image = ImageGrab.grab(rect)
    image = cv2.cvtColor(np.array(image), cv2.COLOR_BGR2GRAY)
    return rect, image

icons = Icons()

def find_icon_location(lushi, icon):
    result = cv2.matchTemplate(lushi, icon, cv2.TM_CCOEFF_NORMED)
    loc = np.where(result >= 0.8)
    pos = []
    for pt in zip(*loc[::-1]):
        near_f = False
        for i in pos:
            distant = (i[0] - pt[0]) ** 2
            if distant < 100:
                near_f = True
        if not near_f:
            pos.append(pt)

    # t_pos = []
    # for i in pos:
    #     t = (i[0] + icon.shape[1]//2 , i[1] + icon.shape[1]//2)
    #     t_pos.append(t)
    # pos = t_pos
    return pos

def check_state(state_name):
    start_time = time.time()
    lushi, image = find_lushi_window()
    for k, v in icons.__dict__.items():
        if k == state_name:
            res = find_icon_location(v, image)
            # print(time.time() - start_time)
            return res



def choose_task(second):
    start_time = time.time()
    while True:
        if check_state("choosetask"):
            print("选择副本")
            combo2()
            return True
        else:
            gift()
            time.sleep(5)
        if time.time() - start_time > second:
            return False

def first_floor(second):
    print("第一层")
    start_time = time.time()
    while True:
        if check_state("start_point"):
            time.sleep(2)
            combo4()
            return True
        if time.time() - start_time > second:
            return False

def fight(second):
    print("战斗")
    start_time = time.time()
    cnt = 0
    while True:
        if check_state("first_battle"):
            # if not check_state("skill_panel_bg"):
            time.sleep(1)
            if cnt != 0:
                # combo3()
                single_hero(2)
            else:
                combo4()
            cnt += 1
        if check_state("ready"):
            combo4()
        if check_state("battle"):
            time.sleep(1)
            if cnt != 0:
                # combo3()
                single_hero(2)
            else:
                combo4()
            cnt += 1
        if check_state("end"):
            combo4()
            print("战斗结束")
            return True
        if time.time() - start_time > second:
            return False

def choose_treasure(second):
    print("选择宝藏")
    start_time = time.time()
    while True:
        if check_state("choose_treasure") or check_state("choose_treasure2"):
            combo5()
            return True
        else:
            combo4()
            time.sleep(2)
        if time.time() - start_time > second:
            return False

def cal_road(surprise_pos):
    side = None
    x = surprise_pos[0][0]
    y = surprise_pos[0][1]
    if x < 380:
        side = "left"
    elif x > 600:
        side = "right"
    else:
        side = "mid"
    if side == "mid":
        lines = check_state("line")
        l = 0
        r = 0
        for line in lines:
            if line[1] > y and line[1] < 500:
                if line[0] > x:
                    r += 1
                else:
                    l += 1
        print("左边:{}段，右边:{}段".format(l, r))
        if l > r:
            side = "left"
        else:
            side = "right"
    return side

def second_floor(second):
    print("第二层选择")
    start_time = time.time()
    while True:
        surprise_pos = check_state("surprise")
        if surprise_pos:
            side = cal_road(surprise_pos)
            print("选择走：{}".format(side))
            time.sleep(1)
            choose_road(side)
            return True
        if time.time() - start_time > second:
            return False

def check_current_state(second):
    print("检查当前状态")
    start_time = time.time()
    while True:
        lushi, image = find_lushi_window()

        for k, v in icons.__dict__.items():
            if not k.startswith('_'):
                res = find_icon_location(v, image)
                if res:
                    return k
        if time.time() - start_time > second:
            return False

def third_floor(second):
    print("第三层")
    start_time = time.time()
    while True:
        surprise_pos = check_state("surprise")
        if surprise_pos:
            if surprise_pos[0][1] < 516:
                x = surprise_pos[0][0]
                y = surprise_pos[0][1]
                pyautogui.click(transpos(surprise_pos[0]))
                time.sleep(1)
                pyautogui.click(transpos(surprise_pos[0]))
                combo4()
                choose_visitor(10)
                return True
        if time.time() - start_time > second:
            return False

def give_up(second):
    print("放弃")
    start_time = time.time()
    while True:
        surprise_pos = check_state("surprise")
        if surprise_pos:
            if surprise_pos[0][1] > 516:
                combo6()
                return True
            else:
                print("没点到神秘选项")
        if time.time() - start_time > second:
            return False

def choose_visitor(second):
    global surprise
    print("选择访客")
    start_time = time.time()
    while True:
        if check_state("visitor"):
            click_visitor(0)
            surprise += 1
            time.sleep(3)
            return True
        else:
            pyautogui.click(transpos((0.8463901689708141, 0.47897196261682246)))
            time.sleep(1)
        if time.time() - start_time > second:
            return False

def main():
    second = 60
    global surprise
    start_time = time.time()
    record = Json("record.json")
    count = record.data["count"]
    surprise = record.data["surprise"]
    used_time = record.data["used_time"]
    while True:
        if count > 0:
            used_time += time.time() - start_time
            record.data["count"] = count
            record.data["surprise"] = surprise
            record.data["used_time"] = used_time
            record.save_json()
            print("神秘选项：{}，神秘人：{}，概率：{}，平均每局用时：{}".format(count, surprise, surprise / count, used_time / count))
        choose_task(second)
        first_floor(second)
        fight(5 * second)
        choose_treasure(second)
        second_floor(second)
        time.sleep(5)
        current_state = check_current_state(second)
        print("当前状态：", current_state)
        if current_state == "first_battle":
            fight(5 * second)
            choose_treasure(second)
        time.sleep(2)
        third_floor(second)
        time.sleep(5)
        give_up(second)
        time.sleep(2)
        count += 1

def main2():
    second = 60
    cnt = 1
    start_time = time.time()
    while True:
        print("平均时间：", (time.time() - start_time) / cnt)
        choose_task(second)
        first_floor(second)
        fight(5 * second)
        choose_treasure(second)
        # give_up(second)
        time.sleep(3)
        combo6()
        cnt += 1

def main3():
    second = 60
    cnt = 0
    start_time = time.time()
    while True:
        if cnt > 0 :
            print("平均时间：", (time.time() - start_time) / cnt)
        choose_task(second)
        first_floor(second)
        fight(5 * second)
        choose_treasure(second)
        # 第二层
        time.sleep(3)
        choose_road("right")
        fight(5 * second)
        choose_treasure(second)
        # 第三层
        time.sleep(3)
        choose_road("right")
        fight(5 * second)
        choose_treasure(second)
        # boss层
        time.sleep(3)
        choose_road("right")
        fight(5 * second)
        time.sleep(12)
        gift()
        time.sleep(3)
        cnt += 1


def test():
    # res = check_state("choosetask")
    if check_state("choosetask"):
        print("choosetask")
        combo2()
    if check_state("start_point"):
        print("start_point")
        combo4()
    if check_state("first_battle"):
        if not check_state("skill_panel_bg"):
            print("skill_select")
            combo3()
        else:
            print("first_battle")
            combo4()
    if check_state("end"):
        print("end")
        combo4()
        print("战斗结束")
    if check_state("choose_treasure"):
        print("choose_treasure")
        combo5()
    surprise_pos = check_state("surprise")
    if surprise_pos:
        side = None
        x = surprise_pos[0][0]
        y = surprise_pos[0][1]
        pyautogui.click((x, y))
        if x < 380:
            side = "left"
        elif x > 600:
            side = "right"
        else:
            side = "mid"
        if side == "mid":
            lines = check_state("line")
            l = 0
            r = 0
            for line in lines:
                if line[1] > y and line[1] < 500:
                    if line[0] > x:
                        r += 1
                    else:
                        l += 1
            print("左边:{}段，右边:{}段".format(l, r))
            if l < r:
                side = "right"
            else:
                side = "left"
        print("选择走：{}".format(side))
        choose_road(side)
main3()
# test()



